import Lazyimg from "./Lazyimg";
import {
  getScollParent
} from "./utils";

//希望Lazyload函数可以返回一个类
export default function Lazyload(Vue) {
  return class Lazy {
    constructor(options) {
      this.options = options;
      this.isAddScrollListner = false;
      this.lazyImgPool = [];
    }

    bindLazy(el, bindings, vnodes) {

      /**
       * console.log(this.options);
       * {
       *   error: "./assets/img/error.jpg",
       *   loading: "./assets/img/loading.gif",
       *   preload: 1
       * }
       */

      // bind(el, bindings, vnode) {
      //   // console.log(el);
      //   //<img alt="【2020最新】『Vue3.0』实战项目深度解析开发技巧经验【JS++】">

      //   /**
      //    * console.log(bindings);
      //    * {
      //    *   def: {bind: ƒ},
      //    *   expression: "item.src",
      //    *   modifiers: {},
      //    *   name: "lazy",
      //    *   rawName: "v-lazy",
      //    *   value: "https://10.idqqimg.com/qqcours..."
      //    * }
      //    */

      //   /**
      //    * console.log(vnode);
      //    * {
      //    *   asyncFactory: undefined,
      //    *   asyncMeta: undefined,
      //    *   children: undefined,
      //    *   componentInstance: undefined,
      //    *   componentOptions: undefined,
      //    *   context: VueComponent {_uid: 1, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …},
      //    *   data: {directives: Array(1), attrs: {…}},
      //    *   elm: img,
      //    *   fnContext: undefined,
      //    *   fnOptions: undefined,
      //    *   fnScopeId: undefined,
      //    *   isAsyncPlaceholder: false,
      //    *   isCloned: false,
      //    *   isComment: false,
      //    *   isOnce: false,
      //    *   isRootInsert: false,
      //    *   isStatic: false,
      //    *   key: undefined,
      //    *   ns: undefined,
      //    *   parent: undefined,
      //    *   raw: false,
      //    *   tag: "img",
      //    *   text: undefined,
      //    *   child: (...)
      //    * }
      //    */
      // }

      //寻找滚动的节点
      //注意：如果直接使用el.parentNode会找不到父节点，el.parentNode = null; 因为此时访问时组件还没加载完毕

      //解决：等待组件挂载完时nextTick()执行后
      Vue.nextTick(() => {
        const scrollParent = getScollParent(el);
        // console.log(scrollParent);
        //<div class="container">...</div>

        //当scrollParent存在 
        //并且 this.isAddScrollListner = true 时
        //才执行绑定scroll事件处理函数
        scrollParent && !this.isAddScrollListner && scrollParent.addEventListener('scroll', this.handleScroll.bind(this), false);

        // console.log(bindings.value);
        //v-lazy="item.src" -> 
        //https://10.idqqimg.com/qqcourse_logo_ng/ajNVdqHZLLDGfnb950qb6Oh3ia6NPuexl2pMzkQDVQjX6Vt3XM6ywrwJdOJFiasm3jibA2UTM1dHO0/356?tp=webp

        //给每张图片进行类实例包装
        const lazyImg = new Lazyimg({
          el,
          src: bindings.value,
          options: this.options,
          imgRender: this.imgRender.bind(this)
        });

        /**
         * console.log(lazyImg);
         * {
         *   el: img,
         *   imgRender: ƒ (),
         *   loaded: false,
         *   options: {
         *     loading: './assets/img/loading.gif', 
         *     error: './assets/img/error.jpg', 
         *     preload: 1
         *   },
         *   src: "https://10.idqqimg.com/...p",
         *   state: {loading: false, error: false}
         * }
         */

        //将所有实例对象放入池里
        this.lazyImgPool.push(lazyImg);

        //首次加载都要执行处理函数
        this.handleScroll();
      });

    }

    //每次滚动时执行
    handleScroll() {
      let isVisible = false;

      this.lazyImgPool.forEach(lazyImg => {
        //没有加载时
        if (!lazyImg.loaded) {
          //检测是否显示在指定区域内
          isVisible = lazyImg.checkIsVisible();

          //isVisible为真时执行方法
          isVisible && lazyImg.laodImg();
        }
      });
    }

    /**
     * 
     * @param {*} lazyImg 实例
     * @param {*} state 'loading' | 'error'
     */
    imgRender(lazyImg, state) {
      const {
        el
      } = lazyImg;
      // console.log(el);
      //<img alt="...">

      let src = '';

      switch (state) {
        case 'loading':
          //如果用户没有写loading时默认为空
          src = lazyImg.options.loading;
          break;
        case 'error':
          src = lazyImg.options.error;
          break;
        default:
          src = lazyImg.src;
          break;
      }

      //设置src的内容
      el.setAttribute('src', src);
    }
  }
}